package cre.sample.test.gc;

/**
 * 内存分配和回收策略测试用例，可以指定不同的GC收集器查看不同的日志
 * +UseSerialGC    Client模式默认，Serial+Serial Old
 * +UseParNewGC    ParNew+Serial Old
 * +UseConcMarkSweepGC ParNew+CMS+Serial Old
 * +UseParallelGC  Server模式默认，Parallel Scavenge+Serial Old
 * +UseParallelOldGC   Parallel Scavenge+Parallel Old
 *
 * @Auther cregu
 */
public class MemoryAllocationPolicy {

    /**
     * 定义1M的字节数
     */
    private final static int _1MB = 1024 * 1024;

    /**
     * VM Args: -verbose:gc -Xms20M -Xmx20M -Xmn10M -XX:+PrintGCDetails -XX:+UseSerialGC
     */
    public static void testAllocation() {
        byte[] allocation1, allocation2, allocation3, allocation4;
        allocation1 = new byte[2 * _1MB]; // 大小为1M个字节，表示大小为1M
        allocation2 = new byte[2 * _1MB];
        allocation3 = new byte[2 * _1MB];
        allocation4 = new byte[4 * _1MB]; // 发生一次Minor GC
    }

    /**
     * VM Args: -verbose:gc -Xms20M -Xmx20M -Xmn10M -XX:+PrintGCDetails -XX:+UseSerialGC
     * -XX:PretenureSizeThreshold=3145728
     */
    public static void testPretenureSizeThreshold(){
        byte[] allocation = new byte[4 * _1MB];//直接放在老年代
    }

    /**
     * VM Args: -verbose:gc -Xms20M -Xmx20M -Xmn10M -XX:+PrintGCDetails -XX:+UseSerialGC
     * -XX:MaxTenuringThreshold=1 -XX:+PrintTenuringDistribution
     */
    public static void testTenuringThreshold() {
        byte[] allocation1, allocation2, allocation3;
        allocation1 = new byte[_1MB /4];
        // 什么时候进入老年代取决于，MaxTenuringThreshold
        allocation2 = new byte[4 * _1MB];
        allocation3 = new byte[4 * _1MB];
        allocation3 = null;
        allocation3 = new byte[4 * _1MB];
    }

    public static void main(String[] args) {
        testTenuringThreshold();
    }

}